<template>
  <div>
    <button @click="takePhoto">拍照</button>
    <video ref="video"></video>
    <canvas ref="canvas"></canvas>
  </div>
</template>

<script>
export default {
  mounted() {
    this.startCamera();
  },
  methods: {
    // 拍照
    takePhoto() {
      this.$refs.canvas.width = this.$refs.video.videoWidth;
      this.$refs.canvas.height = this.$refs.video.videoHeight;
      this.$refs.canvas.getContext("2d").drawImage(this.$refs.video, 0, 0);
    },
    // 启动摄像头
    async startCamera() {
      const stream = await navigator.mediaDevices.getUserMedia({
        video: true,
      });
      this.$refs.video.srcObject = stream;
      this.$refs.video.play();
    },
  },
};
</script>

<style lang="scss" scoped></style>
